<html>

	<head>
		<meta charset="utf-8" />
		<title></title>
		<style type="text/css">
			body {
				margin: 0;
				padding: 0;
			}
			
			.box {
				width: 150px;
				height: 150px;
				position: absolute;
				left: 145px;
				top: 0px;
				border: 1px solid red;
			}
			
			#clip {
				border: 1px solid #999;
				top: 217px;
				left: 536px;
				position: absolute;
			}
		</style>
	</head>

	<body>
		<canvas id="canvas" width=640 height=320></canvas>
		<canvas id="clip" width="100" height="100" style=""></canvas>
		<img id="img" />
		<div id="box" class="box">

		</div><br />
		<p style="color: #999; padding-left: 20px;">
			1. 在选框内按下鼠标<br />
			2. 移动选框<br />
			3. 放开鼠标截图<br />
		</p>
	</body>

</html>

<script type="text/javascript">
	var clip = document.getElementById('clip');
	var canvas = document.getElementById('canvas');
	var box = document.getElementById('box');
	var clipCtx = clip.getContext('2d');
	var context = canvas.getContext('2d');

	//渲染图像
	var img = new Image();
	img.src = 'img/girl2.jpg';
	img.onload = function () {
		context.drawImage(img, 0, 0, canvas.width, canvas.height);
		// 图片加载完毕的时候截图一次
		cut();
	}

	// 按下鼠标
	var isPress = false;
	box.onmousedown = function (ev) {
		isPress = true;
	}
	// 松开鼠标
	box.onmouseup = function (ev) {
		isPress = false;
		cut();
	}
	// 移动鼠标
	document.onmousemove = function (ev) {
		// 鼠标按下才移动
		if (isPress) {
			var x = ev.clientX;
			var y = ev.clientY;
			box.style.left = x - 75;
			box.style.top = y - 75;
		}
	}

	// 截图
	function cut() {
		// 获取截图框的坐标
		var boxX = box.offsetLeft;
		var boxY = box.offsetTop;
		debugger;	

		//裁剪图像: 读取坐标（0，0）宽度100，高度100的区域像素
		var clipImg = context.getImageData(boxX, boxY, 100, 100);
		// 把读取到的像素放入clipCtx里面
		clipCtx.putImageData(clipImg, 0, 0, 0, 0, 100, 100);
	}
</script>